<template>
  <div class="product-cart">
    <s-Header name="购物车" :nomore="false" :noback="false" ></s-Header>
    <!-- 封装navbar-->
    <nav-bar></nav-Bar>

    <!-- 空白提示 -->
    <div class="empty" v-if="!state.list.length">
      <img class="empty-cart" src="https://s.yezgea02.com/1604028375097/empty-car.png" alt="空购物车">
      <div class="title">购物车空空如也</div>
      <van-button round color="#1baeae" type="primary" @click="goTo" block>前往选购</van-button>
    </div>

    <!-- 使用滑动单元格 -->
    <van-checkbox-group v-model="state.result" @change="groupChange">
      <van-swipe-cell v-for="(item, index) in state.list" :key="index">
        <!-- <template #left>
          <van-button square type="primary" text="选择" />
        </template> -->
        <div class="product-content">
          <van-checkbox :name="item.cartItemId" ></van-checkbox>
          <div class="good-img">
            <img :src="$filters.prefix(item.goodsCoverImg)" alt="">
          </div>
          <div class="product-info">
            <div class="top-info">
              {{item.goodsName}}
            </div>
            <div class="bottom-info">
              <span class="price">¥{{item.sellingPrice}} <i>x{{ item.goodsCount }}</i></span>
              <van-stepper 
                integer 
                :name="item.cartItemId"
                button-size="24px" 
                input-width="34px" 
                :min="1"
                :max="5"
                v-model="item.goodsCount"
                async-change
                @change="goodItemNumberChange"
                step="1" />
            </div>
          </div>
        </div>
        <template #right>
          <van-button 
            square 
            icon="delete"
            type="danger" 
            @click="deleteGood(item.cartItemId)"
            />
        </template>
      </van-swipe-cell>
    </van-checkbox-group>
    
    <!-- 提交订单bar -->
    <van-submit-bar 
      v-if="state.list.length" 
      class="submit-all van-hairline--top" 
      :price="getCount"  
      button-text="结 算"
      @submit="onSubmit">
      <van-checkbox @click="allCheck" v-model="state.checkAll" >全选</van-checkbox>
      <!-- <template #tip>
        你的收货地址不支持配送, <span @click="onClickLink">修改地址</span>
      </template> -->
    </van-submit-bar>
  </div>
</template>
<script setup>
  import { useRoute, useRouter } from 'vue-router'
  import { reactive, ref, isRef, isReactive,nextTick, computed, onUnmounted, onMounted  } from 'vue'
  import { showSuccessToast, showFailToast, showLoadingToast, closeToast } from 'vant'
  import { setLocal, getLocal } from '@/common/js/utils'
  import sHeader from '@/components/SimpleHeader.vue'
  import navBar from '@/components/NavBar.vue'
  import { getCart, deleteCartItem, modifyCart } from '@/service/cart'
  import { useCartStore } from '@/stores/cart'

  const cart = useCartStore()
  const router = useRouter();
  const route = useRoute();
  console.log('router...',router,route)
  const state = reactive({
    checked: false,
    list: [], // 商品列表
    all: false,
    result: [], // 通过van-checkbox-group处理的选中goodId
    checkAll: true, // 是否全选
    checkAll2:true
  })
  const getCount = computed(()=> {
    const selestedData = state.list.filter(item=> state.result.includes(item.cartItemId));
    return selestedData.reduce((pre,cur)=>{ return cur.goodsCount * cur.sellingPrice * 100 + pre},0)
  })
  onMounted(()=>{
    init();
  })

  const init = async () => { // 获取最新商品信息
    showLoadingToast({ message: '加载中...', forbidClick: true });
    const { data } = await getCart({ pageNumber: 1 })
    state.list = data;
    state.result = data.map(item => item.cartItemId)
    closeToast()
  }

  const onSubmit = () => {
    if (state.result.length == 0) {
      showFailToast('请选择商品进行结算')
      return
    }
    const params = JSON.stringify(state.result)
    router.push({ path: '/create-order', query: { cartItemIds: params } })
  }
  const onClickLink = () => {
    // router.go(-1)  
  }

  const goodItemNumberChange = async (value, detail)=>{ // 修某项的数据
    console.log('goodItemNumberChange...',value, detail)
    const currentItemId = detail.name;
    const currentGood = state.list.find(item=> item.cartItemId === currentItemId)
    console.log(4444444,currentGood)
    if (value > 5) {
      showFailToast('超出单个商品的最大购买数量');
      // van-stepper 当不设置max 二次手动修改值在input中展示值不会更新 ???
      currentGood.goodsCount = 5;
      return
    }
    if (value < 1) {
      showFailToast('商品不得小于0')
      return
    }
    showLoadingToast({ message: '修改中...', forbidClick: true });
    const params = {
      cartItemId: detail.name,
      goodsCount: value
    }
    await modifyCart(params)
    currentGood.goodsCount = value;
    closeToast();
  }
  const deleteGood = async (goodId) => { // 删除该项产品
    await deleteCartItem(goodId)
    cart.updateCart()
    init()  
  }

  const allCheck = () => { // 全选
    console.log('allCheck...',state.checkAll)
    if(state.checkAll){
      state.result =  state.list.map(item => item.cartItemId)
    } else {
      state.result = []
    }
  }
  const groupChange = (names) => { // checkGroup改变
    console.log('grounpChange...',names);
    if (names.length == state.list.length) {
      state.checkAll = true
    } else {
      state.checkAll = false
    }
    state.result = names
  }

  const goBack = () => {
    router.go(-1)
  }
  const goTo = (r, query) => {
    router.push({ path: '/home' })
  }
</script>
  

<style lang="less" >
  .product-cart{
    .van-checkbox-group{
      // height: calc(100% - 144px);
      overflow: scroll;
      // margin-top:44px;
      margin-bottom:90px;
    } 
    .van-submit-bar__bar{
      // border-top: 1px solid #ebedf0;
    }
  }
</style>
<style lang="less" scoped>
  .product-cart{
    height: 100%;
    .van-swipe-cell{
      margin: 6px 0px;
      box-shadow: 1px 1px 4px 0px #ccc;
      .product-content{
        width: 100%;
        height:110px;
        display: flex;
        align-items: center;
        padding: 5px 10px;
        .van-checkbox{
          flex-basis: 40px;
        }
        img{
          width: 100px;
          height: 100px;
        }
        .product-info{
          height: 100%;
          width: 100%;
          padding-top:6px;
          padding-bottom:6px;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          padding-left: 10px;
          .top-info{
            font-size:12px;
            font-family: Avenir, Helvetica, Arial, sans-serif;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
            color: #2c3e50;
            text-overflow: ellipsis;
            -webkit-line-clamp: 3;
            line-break: anywhere;
            -webkit-box-orient: vertical;
            display: -webkit-box;
            overflow: hidden;
          }
          .bottom-info{
            width: 100%;
            display: flex;
            flex:1;
            justify-content: space-between;
            align-items: flex-end;
            .price{
              font-size: 16px;
              color: red;
              line-height: 28px;
              i{
                font-size: 13px;
                padding-left: 2px;
                color: #2c3e50;
              }
            }
          }
        }
      }
      .van-swipe-cell__right{
        .van-button{
          height: 100%;
        }
      }
    }
    .empty{
      display: flex;
      flex-direction: column;
      align-items: center;   
      margin:100px 90px 0px;   
      .empty-cart{
        width: 200px;
        margin-bottom:12px;
      }
      .title{
        font-size: 16px;
        margin-bottom: 20px;
      }
      .primary{
        width: 160px;
      }
    }
    .submit-all{
      margin-bottom: 50px;
    }
    // .van-submit-bar__bar{
    //   border-top: 1px solid #ccc;
    // }
  }
</style>